using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using AvansRS.Domain;
using AvansRS.Domain.DataInterface;
using AvansRS.Web.Util;
using AvansRS.Data;
using System.ComponentModel.DataAnnotations;

namespace AvansRS.Web.Controllers
{
    public class RegisterController : Controller
    {
        private IRepository<Registration> _registrationRepository;
        private IRepository<EventDate> _eventDateRepository;
        private IRepository<TimeBlock> _timeBlockRepository;
        private IEventRepository _eventRepository;

        public RegisterController(IRepository<Registration> registrationRepository, 
                                  IRepository<EventDate> eventDateRepository,
                                  IRepository<TimeBlock> timeBlockRepository,
                                  IEventRepository eventRepository)
        {
            _registrationRepository = registrationRepository;
            _eventDateRepository = eventDateRepository;
            _timeBlockRepository = timeBlockRepository;
            _eventRepository = eventRepository;
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult RegisterOnEventDate(int id)
        {
            EventDate eventDate = _eventDateRepository.GetByID(id);

            return View(eventDate);
        }
        
        public JsonResult RegisterOnEvent(int eventDateID, int timeBlockID)
        {
            try
            {
                Registration registration = new Registration();

                EventDate eventDate = _eventDateRepository.GetByID(eventDateID);
                TimeBlock timeBlock = _timeBlockRepository.GetByID(timeBlockID);

                registration.EventDate = eventDate;
                registration.TimeBlock = timeBlock;

                Person person = SessionHelper.GetLoggedIn(User);
                registration.Entity = person.Entity;

                eventDate.Register(registration);
                _registrationRepository.Add(registration);
                _eventDateRepository.Save(eventDate);

                return Json(true);
            }
            catch (DataException exception)
            {
                return Json(false);
            }
            catch (ValidationException exception)
            {
                return Json(false);
            }
            catch(DomainException ex)
            {
                return Json(false);
            }
        }

        public ActionResult EventDates(int id)
        {
            Event @event = _eventRepository.GetByID(id);

            return View(@event.EventDates);
        }

        public ActionResult ViewRegistrations(int id)
        {
            EventDate eventDate = _eventDateRepository.GetByID(id);

            return View(eventDate);
        }
    }
}
